home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_03 / allison / rounderr.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-01-03  |  819 b   |  41 lines

  1. LISTING 1 - Shows roundoff error in computing powers of e
  2.  
  3. #include <stdio.h>
  4. #include <math.h>
  5.  
  6. double e(double x);
  7.  
  8. main()
  9. {
  10.     printf("e(55.5) == %g, exp(55.5) == %g\n",
  11.            e(55.5), exp(55.5));
  12.     printf("e(-55.5) == %g, exp(-55.5) == %g\n",
  13.            e(-55.5), exp(-55.5));
  14.     printf("1/e(55.5) == %g\n",1.0 / e(55.5));
  15.     return 0;
  16. }
  17.  
  18. double e(double x)
  19. {
  20.     double sum1 = 1.0;
  21.     double sum2 = 1.0 + x;
  22.     double term = x;
  23.     int i = 1;
  24.  
  25.     /* Calculate exp(x) via Taylor Series */
  26.     while (sum1 != sum2)
  27.     {
  28.         sum1 = sum2;
  29.         term = term * x / ++i;
  30.         sum2 += term;
  31.     }
  32.     return sum2;
  33. }
  34.  
  35. /* Output:
  36. e(55.5) == 1.26866e+24, exp(55.5) == 1.26866e+24
  37. e(-55.5) == -6.76351e+06, exp(-55.5) == 7.88236e-25
  38. 1/e(55.5) == 7.88236e-25
  39. */
  40.  
  41.